import { Component, OnInit, OnDestroy, ViewChild } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule, FormGroup, FormBuilder, Validators } from '@angular/forms';
import { ListService, PagedResultDto } from '@abp/ng.core';
import { ThemeSharedModule } from '@abp/ng.theme.shared';
import { ShopService } from './shop.service';
import { ShopDto, CreateUpdateShopDto } from './models';
import { ConfirmationService, Confirmation } from '@abp/ng.theme.shared';
import { ToasterService } from '@abp/ng.theme.shared';
import { Subscription } from 'rxjs';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { finalize } from 'rxjs/operators';
import { ExcelExportService } from '../shared/services/excel-export.service';
import { NgbModalModule } from '@ng-bootstrap/ng-bootstrap';
import { SharedModule } from '../shared/shared.module';

@Component({
  selector: 'app-shops',
  standalone: true,
  imports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule,
    ThemeSharedModule,
    NgbModalModule,
    SharedModule
  ],
  templateUrl: './shops.component.html',
  styleUrl: './shops.component.scss',
  providers: [ListService]
})
export class ShopsComponent implements OnInit, OnDestroy {
  shop = { items: [], totalCount: 0 } as PagedResultDto<ShopDto>;
  createShopForm: FormGroup;
  isModalOpen = false;
  isEditMode = false;
  selectedShopId: string;
  isSaving = false;
  Math = Math; // 添加Math对象以在模板中使用
  
  // 复选框相关变量
  selectedItems: string[] = []; // 存储选中项ID
  isAllSelected = false; // 全选标记
  
  // 分类选项
  categoryOptions: string[] = [
    '日用品',
    '食品',
    '饮料',
    '电子产品',
    '家具',
    '服装',
    '化妆品',
    '玩具',
    '书籍',
    '其他'
  ];
  
  // 商品类型选项
  productTypeOptions: string[] = ['普通商品', '贵重品', '易碎品', '危险品', '温控商品'];
  
  // 商品属性选项
  productAttributeOptions: string[] = ['常温', '冷藏', '冷冻', '恒温'];
  
  // 单位选项
  unitOptions: string[] = ['件', '箱', '托盘', '个', '包'];

  // 保质期单位选项
  shelfLifeDaysUnitOptions: string[] = ['天', '月', '年'];

  // 计费类型选项
  billingTypeOptions: string[] = ['按件', '按重量', '按体积', '按托'];
  
  // 分页相关变量
  pageSizeOptions = [10, 20, 30, 50];
  currentPageSize = 10;
  maxPageCount = 1; // 最大页数
  visiblePageNumbers: number[] = []; // 可见页码数组
  inputPageNumber: number = 1; // 输入的页码
  
  // 订阅对象
  private subscription: Subscription = new Subscription();
  
  // 添加搜索关键字属性
  productNameKeyword = '';
  isSearchMode = false;
  
  // 高级搜索字段
  searchFilter = {
    filter: '',
    productName: '',
    productCode: '',
    category: '',
    productType: '',
    ownerCode: ''
  };
  
  // 添加加载状态
  isLoading = false;
  
  // 添加导出状态
  isExporting = false;
  
  constructor(
    public readonly list: ListService,
    private shopService: ShopService,
    private fb: FormBuilder,
    private confirmation: ConfirmationService,
    private toaster: ToasterService,
    private modalService: NgbModal,
    private excelExportService: ExcelExportService
  ) {
    this.createShopForm = this.fb.group({
      id: [null],
      productName: ['', Validators.required],
      englishName: [''],
      japaneseName: [''],
      specification: [''],
      ownerCode: ['', Validators.maxLength(50)],
      customerProductCode: ['', Validators.maxLength(50)],
      productAttribute: ['', Validators.maxLength(50)],
      category: ['', Validators.maxLength(50)],
      productType: ['', Validators.maxLength(50)],
      splitControl: ['', Validators.maxLength(20)],
      trayLayerCount: [null],
      trayHeight: [null],
      billingType: ['', Validators.maxLength(50)],
      barcode: ['', Validators.maxLength(50)],
      shelfLifeDaysUnit: ['', Validators.maxLength(20)],
      splitUnit: ['', Validators.maxLength(20)],
      volume: [null],
      weight: [null],
      splitQuantity: [null],
      price: [null],
      length: [null],
      width: [null],
      height: [null],
      sku: ['', Validators.maxLength(50)],
      tingyong: [0, Validators.required]
    });
  }

  ngOnInit() {
    console.log('ShopsComponent 初始化中...');
    
    // 初始化时确保页码是1
    this.list.page = 1;
    this.loadData();
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }

  // 加载数据并处理分页
  loadData() {
    // 确保页面在有效范围内
    if (this.list.page <= 0) {
      this.list.page = 1;
    }
    
    // 设置加载状态
    this.isLoading = true;
    
    const streamCreator = (query) => {
      // 使用普通列表方法
      const params = {
        ...query,
        maxResultCount: this.currentPageSize,
        skipCount: (this.list.page - 1) * this.currentPageSize
      };
      
      console.log('API请求参数:', params); // 添加调试日志
      
      // 根据是否在搜索模式选择不同的API
      if (this.isSearchMode && this.productNameKeyword.trim()) {
        return this.shopService.searchByName(this.productNameKeyword, params);
      } else {
        return this.shopService.getList(params);
      }
    };
    
    this.subscription.add(
      this.list.hookToQuery(streamCreator)
        .pipe(
          finalize(() => {
            this.isLoading = false; // 请求结束后，无论成功还是失败，都重置加载状态
            this.selectedItems = []; // 清空选中项
            this.isAllSelected = false; // 重置全选状态
          })
        )
        .subscribe(
          (response: PagedResultDto<ShopDto>) => {
            console.log('API响应数据:', response); // 添加调试日志
            this.shop = response;
            // 计算最大页数
            if (response.totalCount > 0) {
              this.maxPageCount = Math.ceil(response.totalCount / this.currentPageSize);
              
              // 如果当前页超出最大页数，则返回到最后一页
              if (this.list.page > this.maxPageCount) {
                this.list.page = this.maxPageCount;
                // 重新加载正确的页数据，但不要造成无限循环
                if (response.items.length === 0) {
                  this.loadDataWithoutCheck();
                }
              }
            } else {
              this.maxPageCount = 1;
              this.list.page = 1;
            }
            
            // 更新页码显示
            this.updateVisiblePageNumbers();
          },
          error => {
            console.error('加载数据失败', error);
            // 详细记录错误信息
            console.error('错误详情:', {
              status: error.status,
              statusText: error.statusText,
              error: error.error,
              message: error.message
            });
            
            let errorMessage = '加载数据失败，请稍后重试';
            if (error && error.error && error.error.message) {
              errorMessage = `${errorMessage}: ${error.error.message}`;
            }
            this.toaster.error(errorMessage, '错误', { life: 7000 });
          }
        )
    );
  }
  
  // 不进行页码检查的数据加载方法，避免循环
  loadDataWithoutCheck() {
    // 设置加载状态
    this.isLoading = true;
    
    const streamCreator = (query) => {
      // 使用普通列表方法
      const params = {
        ...query,
        maxResultCount: this.currentPageSize,
        skipCount: (this.list.page - 1) * this.currentPageSize
      };
      
      // 根据是否在搜索模式选择不同的API
      if (this.isSearchMode && this.productNameKeyword.trim()) {
        return this.shopService.searchByName(this.productNameKeyword, params);
      } else {
        return this.shopService.getList(params);
      }
    };
    
    this.subscription.add(
      this.list.hookToQuery(streamCreator)
        .pipe(
          finalize(() => {
            this.isLoading = false; // 请求结束后，无论成功还是失败，都重置加载状态
          })
        )
        .subscribe(
          (response: PagedResultDto<ShopDto>) => {
            this.shop = response;
            this.updateVisiblePageNumbers();
          },
          error => {
            console.error('加载数据失败', error);
            let errorMessage = '加载数据失败，请稍后重试';
            if (error && error.error && error.error.message) {
              errorMessage = `${errorMessage}: ${error.error.message}`;
            }
            this.toaster.error(errorMessage, '错误', { life: 7000 });
          }
        )
    );
  }

  // 更新可见页码
  updateVisiblePageNumbers() {
    // 根据当前页码计算显示哪些页码按钮
    // 显示策略：当前页码前后各显示2个，总共最多显示5个页码
    const currentPage = this.list.page || 1;
    const pageNumbers = [];
    
    // 始终显示第一页
    pageNumbers.push(1);
    
    // 计算显示的页码范围
    let startPage = Math.max(2, currentPage - 2);
    let endPage = Math.min(this.maxPageCount - 1, currentPage + 2);
    
    // 如果当前页接近开始，调整结束页
    if (currentPage <= 3) {
      endPage = Math.min(5, this.maxPageCount - 1);
    }
    
    // 如果当前页接近结束，调整开始页
    if (currentPage >= this.maxPageCount - 2) {
      startPage = Math.max(2, this.maxPageCount - 4);
    }
    
    // 添加省略号指示符（如果需要）
    if (startPage > 2) {
      pageNumbers.push(-1); // 用-1表示省略号
    }
    
    // 添加中间页码
    for (let i = startPage; i <= endPage; i++) {
      pageNumbers.push(i);
    }
    
    // 添加省略号指示符（如果需要）
    if (endPage < this.maxPageCount - 1) {
      pageNumbers.push(-2); // 用-2表示省略号
    }
    
    // 添加最后一页（如果不是第一页）
    if (this.maxPageCount > 1) {
      pageNumbers.push(this.maxPageCount);
    }
    
    this.visiblePageNumbers = pageNumbers;
  }
  
  // 处理每页大小变化
  onPageSizeChange(pageSize: number) {
    this.currentPageSize = pageSize;
    this.list.page = 1; // 重置到第一页
    this.loadData();
  }
  
  // 跳转到指定页
  goToPage(page: number) {
    if (page >= 1 && page <= this.maxPageCount && page !== this.list.page) {
      this.list.page = page;
      this.loadData();
    }
  }
  
  // 处理输入页码变化
  onPageInputChange(event: Event) {
    const input = event.target as HTMLInputElement;
    const value = parseInt(input.value, 10);
    
    if (!isNaN(value)) {
      this.inputPageNumber = Math.min(Math.max(1, value), this.maxPageCount);
    } else {
      this.inputPageNumber = 1;
    }
  }
  
  // 处理页码输入框按键事件
  onPageInputKeyUp(event: KeyboardEvent) {
    if (event.key === 'Enter') {
      this.goToPage(this.inputPageNumber);
    }
  }
  
  // 打开创建模态框
  openCreateModal(modal) {
    this.isEditMode = false;
    this.createShopForm.reset();
    
    // 一些可能的默认值
    this.createShopForm.patchValue({
      splitControl: '否',
      tingyong: 0
    });
    
    this.isModalOpen = true;
    this.modalService.open(modal, { 
      size: 'lg',
      backdrop: 'static'
    });
  }
  
  // 打开编辑模态框
  openEditModal(shopId: string, modal) {
    this.isEditMode = true;
    this.selectedShopId = shopId;
    this.isLoading = true;
    
    this.shopService.getById(shopId).subscribe(
      (shop: ShopDto) => {
        this.createShopForm.patchValue({
          id: shop.id,
          productName: shop.productName || '',
          englishName: shop.englishName || '',
          japaneseName: shop.japaneseName || '',
          specification: shop.specification || '',
          ownerCode: shop.ownerCode || '',
          customerProductCode: shop.customerProductCode || '',
          productAttribute: shop.productAttribute || '',
          category: shop.category || '',
          productType: shop.productType || '',
          splitControl: shop.splitControl || '否',
          trayLayerCount: shop.trayLayerCount || null,
          trayHeight: shop.trayHeight || null,
          billingType: shop.billingType || '',
          barcode: shop.barcode || '',
          shelfLifeDaysUnit: shop.shelfLifeDaysUnit || '',
          splitUnit: shop.splitUnit || '',
          volume: shop.volume || null,
          weight: shop.weight || null,
          splitQuantity: shop.splitQuantity || null,
          price: shop.price || null,
          length: shop.length || null,
          width: shop.width || null,
          height: shop.height || null,
          sku: shop.sku || '',
          tingyong: shop.tingyong ?? 0
        });
        
        this.isLoading = false;
        this.isModalOpen = true;
        this.modalService.open(modal, { 
          size: 'lg',
          backdrop: 'static'
        });
      },
      error => {
        this.isLoading = false;
        let errorMessage = '获取商品信息失败，请稍后重试';
        if (error && error.error && error.error.message) {
          errorMessage = `${errorMessage}: ${error.error.message}`;
        }
        this.toaster.error(errorMessage, '错误', { life: 7000 });
      }
    );
  }
  
  // 关闭模态框
  closeModal() {
    this.isModalOpen = false;
    this.modalService.dismissAll();
  }
  
  // 保存商品
  save() {
    if (this.createShopForm.invalid) {
      // 标记所有表单控件为touched，以显示验证错误
      for (const i in this.createShopForm.controls) {
        this.createShopForm.controls[i].markAsDirty();
        this.createShopForm.controls[i].updateValueAndValidity();
      }
      return;
    }
    
    this.isSaving = true;
    const shopData: any = this.createShopForm.value;
    
    if (this.isEditMode) {
      this.shopService.update(this.selectedShopId, shopData as CreateUpdateShopDto)
        .subscribe(
          () => {
            this.toaster.success('商品更新成功！', '成功');
            this.isSaving = false;
            this.closeModal();
            this.loadData();
          },
          error => {
            this.isSaving = false;
            let errorMessage = '更新商品失败，请稍后重试';
            if (error && error.error && error.error.message) {
              errorMessage = `${errorMessage}: ${error.error.message}`;
            }
            this.toaster.error(errorMessage, '错误', { life: 7000 });
          }
        );
    } else {
      delete shopData.id;
      this.shopService.create(shopData as CreateUpdateShopDto)
        .subscribe(
          () => {
            this.toaster.success('商品创建成功！', '成功');
            this.isSaving = false;
            this.closeModal();
            this.loadData();
          },
          error => {
            this.isSaving = false;
            let errorMessage = '创建商品失败，请稍后重试';
            if (error && error.error && error.error.message) {
              errorMessage = `${errorMessage}: ${error.error.message}`;
            }
            this.toaster.error(errorMessage, '错误', { life: 7000 });
          }
        );
    }
  }
  
  // 删除商品
  deleteShop(shopId: string) {
    this.confirmation.warn(
      '删除确认',
      '您确定要删除这个商品吗？',
      { messageLocalizationParams: [] }
    ).subscribe((status) => {
      if (status === Confirmation.Status.confirm) {
        this.shopService.delete(shopId).subscribe(
          () => {
            this.toaster.success('商品删除成功！', '成功');
            this.loadData();
          },
          error => {
            let errorMessage = '删除商品失败，请稍后重试';
            if (error && error.error && error.error.message) {
              errorMessage = `${errorMessage}: ${error.error.message}`;
            }
            this.toaster.error(errorMessage, '错误', { life: 7000 });
          }
        );
      }
    });
  }
  
  // 搜索商品
  searchShop() {
    this.isSearchMode = true;
    this.list.page = 1; // 重置到第一页
    this.loadData();
  }
  
  // 重置搜索
  resetSearch() {
    this.isSearchMode = false;
    this.productNameKeyword = '';
    this.searchFilter = {
      filter: '',
      productName: '',
      productCode: '',
      category: '',
      productType: '',
      ownerCode: ''
    };
    this.list.page = 1; // 重置到第一页
    this.loadData();
  }
  
  // 导出选中的商品
  async exportSelectedItems() {
    if (this.selectedItems.length === 0) {
      this.toaster.info('请先选择要导出的商品', '提示');
      return;
    }
    
    this.isExporting = true;
    
    try {
      // 获取选中的商品数据
      const items = this.shop.items.filter(item => this.selectedItems.includes(item.id));
      
      // 定义表头
      const headers = [
        { header: '商品ID', key: 'id', width: 20 },
        { header: '商品名称', key: 'productName', width: 20 },
        { header: 'SKU', key: 'sku', width: 20 },
        { header: '货主代码', key: 'ownerCode', width: 15 },
        { header: '规格', key: 'specification', width: 20 },
        { header: '商品类型', key: 'productType', width: 15 },
        { header: '条码', key: 'barcode', width: 20 }
      ];
      
      await this.excelExportService.exportToExcel(items, '选中商品数据-商品列表', headers);
      
      this.toaster.success('导出成功！', '成功');
    } catch (error) {
      console.error('导出失败', error);
      this.toaster.error('导出失败，请稍后重试', '错误');
    } finally {
      this.isExporting = false;
    }
  }
  
  // 导出当前页
  async exportCurrentPage() {
    if (this.shop.items.length === 0) {
      this.toaster.info('当前页没有数据可导出', '提示');
      return;
    }
    
    this.isExporting = true;
    
    try {
      // 定义表头
      const headers = [
        { header: '商品ID', key: 'id', width: 20 },
        { header: '商品名称', key: 'productName', width: 20 },
        { header: 'SKU', key: 'sku', width: 20 },
        { header: '货主代码', key: 'ownerCode', width: 15 },
        { header: '规格', key: 'specification', width: 20 },
        { header: '商品类型', key: 'productType', width: 15 },
        { header: '条码', key: 'barcode', width: 20 }
      ];
      
      await this.excelExportService.exportToExcel(this.shop.items, '当前页商品数据-商品列表', headers);
      
      this.toaster.success('导出成功！', '成功');
    } catch (error) {
      console.error('导出失败', error);
      this.toaster.error('导出失败，请稍后重试', '错误');
    } finally {
      this.isExporting = false;
    }
  }
  
  // 导出全部数据
  exportAllData() {
    if (this.shop.totalCount === 0) {
      this.toaster.info('没有数据可导出', '提示');
      return;
    }
    
    this.isExporting = true;
    
    // 定义获取全部数据的函数
    const fetchAllData = () => {
      // 计算需要请求的页数
      const pageSize = 1000; // 每页大小设置为较大值，减少请求次数
      const pageCount = Math.ceil(this.shop.totalCount / pageSize);
      const allItems = [];
      
      // 定义递归获取数据的函数
      const fetchPage = (page: number) => {
        const params = {
          skipCount: (page - 1) * pageSize,
          maxResultCount: pageSize
        };
        
        // 根据当前模式选择API
        let request;
        if (this.isSearchMode && this.productNameKeyword.trim()) {
          request = this.shopService.searchByName(this.productNameKeyword, params);
        } else {
          request = this.shopService.getList(params);
        }
        
        return request.toPromise()
          .then((response: any) => {
            allItems.push(...response.items);
            
            if (page < pageCount) {
              return fetchPage(page + 1);
            }
            
            return allItems;
          });
      };
      
      // 开始获取第一页
      return fetchPage(1);
    };
    
    // 获取并导出所有数据
    fetchAllData()
      .then(async allItems => {
        try {
          // 定义表头
          const headers = [
            { header: '商品ID', key: 'id', width: 20 },
            { header: '商品名称', key: 'productName', width: 20 },
            { header: 'SKU', key: 'sku', width: 20 },
            { header: '货主代码', key: 'ownerCode', width: 15 },
            { header: '规格', key: 'specification', width: 20 },
            { header: '商品类型', key: 'productType', width: 15 },
            { header: '条码', key: 'barcode', width: 20 }
          ];
          
          await this.excelExportService.exportToExcel(allItems, '全部商品数据-商品列表', headers);
          
          this.toaster.success('导出成功！', '成功');
        } catch (error) {
          console.error('导出失败', error);
          this.toaster.error('导出失败，请稍后重试', '错误');
        }
      })
      .catch(error => {
        console.error('获取数据失败', error);
        this.toaster.error('获取数据失败，导出中断', '错误');
      })
      .finally(() => {
        this.isExporting = false;
      });
  }
  
  // 全选/取消全选
  selectAll(checked: boolean): void {
    this.isAllSelected = checked;
    this.selectedItems = checked ? 
      this.shop.items.map(item => item.id) : [];
  }
  
  // 切换单个项目的选中状态
  toggleItemSelection(id: string): void {
    const index = this.selectedItems.indexOf(id);
    if (index > -1) {
      this.selectedItems.splice(index, 1);
    } else {
      this.selectedItems.push(id);
    }
    
    // 更新全选状态
    this.isAllSelected = this.shop.items.length > 0 && 
      this.selectedItems.length === this.shop.items.length;
  }
  
  // 批量删除
  deleteSelected(): void {
    if (this.selectedItems.length === 0) {
      this.toaster.info('请先选择要删除的商品', '提示');
      return;
    }
    
    this.confirmation.warn(
      '批量删除确认',
      `您确定要删除选中的 ${this.selectedItems.length} 项商品吗？`,
      { messageLocalizationParams: [] }
    ).subscribe((status) => {
      if (status === Confirmation.Status.confirm) {
        let completedCount = 0;
        let failedCount = 0;
        
        // 显示正在删除的提示
        const loadingToastId = this.toaster.info(
          `正在删除商品...`,
          '处理中',
          { sticky: true }
        );
        
        // 对每个选中的项目执行删除
        this.selectedItems.forEach(id => {
          this.shopService.delete(id).subscribe(
            () => {
              completedCount++;
              this.checkDeleteCompletion(completedCount, failedCount, loadingToastId);
            },
            () => {
              failedCount++;
              this.checkDeleteCompletion(completedCount, failedCount, loadingToastId);
            }
          );
        });
      }
    });
  }
  
  // 检查删除是否全部完成
  private checkDeleteCompletion(completed: number, failed: number, loadingToastId: any): void {
    const total = this.selectedItems.length;
    
    if (completed + failed === total) {
      // 关闭加载提示
      if (loadingToastId) {
        this.toaster.clear(loadingToastId);
      }
      
      // 显示结果
      if (failed === 0) {
        this.toaster.success(`成功删除 ${completed} 项商品`, '成功');
      } else if (completed === 0) {
        this.toaster.error(`删除失败，请稍后重试`, '错误');
      } else {
        this.toaster.info(`删除完成，成功: ${completed}，失败: ${failed}`, '部分成功');
      }
      
      // 重新加载数据
      this.loadData();
    }
  }
} 